package lt.laimis.shop.web.action.node;

import lt.laimis.shop.web.action.BaseAction;
import lt.laimis.shop.service.node.Node;
import net.sourceforge.stripes.action.*;

import java.io.StringReader;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

/**
 * Created by IntelliJ IDEA.
 * User: laimis
 * Date: Jul 17, 2008
 * Time: 5:07:09 PM
 * To change this template use File | Settings | File Templates.
 */
@UrlBinding("/node/action.do")
public class NodeAcionBean extends BaseAction {
    private String nodeRef = "";
    private List<Node> subCategorys;
    private List<Node> categorys;
    private String activeCategory;
    private String currentNode;

    public String getCurrentNode() {
        return currentNode;
    }

    public void setCurrentNode(String currentNode) {
        this.currentNode = currentNode;
    }

    public String getActiveCategory() {
        return activeCategory;
    }

    public void setActiveCategory(String activeCategory) {
        this.activeCategory = activeCategory;
    }

    public List<Node> getCategorys() {
        if (this.categorys == null && nodeService != null) {
            this.categorys = nodeService.getNodesByParentId("");
        }
        return categorys;
    }

    public void setCategorys(List<Node> categorys) {
        this.categorys = categorys;
    }

    public String getNodeRef() {
        return nodeRef;
    }

    public void setNodeRef(String nodeRef) {
        this.nodeRef = nodeRef;
        this.activeCategory = nodeRef; 
    }

    @HandlesEvent("getSubCategorys")
    public Resolution getSubCategorys() throws JSONException {
        if (this.subCategorys == null && nodeService != null) {
            this.subCategorys = nodeService.getNodesByParentId(getNodeRef());
        }
        String result = toJSONNodes(this.subCategorys);
        return new StreamingResolution("text", new StringReader(result));
    }


    @DefaultHandler
    public Resolution process() throws Exception {
        return new RedirectResolution("/index.jsp");
    }


    public String toJSONNodes(List<Node> nodeLlist) throws JSONException {
        JSONArray nodeList = new JSONArray();
        for (Node item : nodeLlist) {
            JSONObject ci = new JSONObject();
            ci.put("nodeId", item.getNodeId());
            ci.put("type", item.getType());
            ci.put("name", item.getName());
            ci.put("title", item.getTitle());
            ci.put("description", item.getDescpription());
            nodeList.put(ci);
        }
        return nodeList.toString();
    }

}
